import Taro, {Component} from '@tarojs/taro'
import {View, Text, Input, Textarea, Button, Picker} from '@tarojs/components'
import {connect} from '@tarojs/redux'
import {courseListActions} from '../../actions/courseList'
import {actions as tabPageActions} from "../../actions/tabPage";
import {
    AtInput,
    AtForm,
    AtTextarea,
    AtImagePicker,
    AtSwitch,
    AtButton,
    AtModal,
    AtModalHeader,
    AtModalContent,
    AtModalAction
} from 'taro-ui'

import {SCOPE_USERLOCATION} from '../../constants'

import {url} from '../../utils/request'


import './index.scss';
import {bindActionCreators} from "redux";
import {detailActions} from "../../actions/detail";

class Creator extends Component {

    constructor(props) {
        super(props);
        this.state = {
            showModal: false
        }
    }

    componentWillMount() {
        console.log(this.props.form.startDate,!this.props.form.startDate)
        if (!this.props.form.startDate) {
            this.props.initForm()
        }
    }

    // AtInput
    handleChange(prop, value) {
        this.props.changeForm(prop, value)
    }

    // AtTextarea AtPicker
    handleTextareaChange(prop, e) {
        const value = e.detail.value
        this.props.changeForm(prop, value)
    }

    // AtImagePicker
    handleImageChange(files,e) {
        if(e === 'add'){
            // 后端在此只返回图片id，所以pickedImages中放入前端文件地址
            // 虽然已经在UI层面防止了多次图片上传，然而考虑方法被调用的潜在bug可能性，这个判断要保留
            if(this.props.form.banner_blob_id) {
                Taro.showToast({title:'必须先移除图片',icon: 'none'})
                return
            }
            const file = files[files.length - 1]
            Taro.uploadFile({
                url: url.uploadBannerImg,
                filePath: file.url,
                name: 'banner_img',
            }).then(res => {
                const banner_file = JSON.parse(res.data);
                console.log('文件上传 blob_id：', banner_file.blob_id, 'URL: ', banner_file.filelink);
                this.props.changeFormMultipart({pickedImages: [file], banner_blob_id: banner_file.blob_id})
            }).catch(error => {
                console.error('文件上传失败', error)
            })

        }else if(e === 'remove'){
            this.props.changeFormMultipart({pickedImages: [], banner_blob_id: null})
        }

    }

    handleFormSubmit() {
        this.props.createCourse(this.props.form);
    }

    handleClickChooseMap() {
        Taro.getSetting().then(setting => {
            const permited = setting.authSetting && setting.authSetting[SCOPE_USERLOCATION]
            if (permited) {
                this.chooseLocation()
            } else {
                Taro.authorize({scope: SCOPE_USERLOCATION}).then(res => {
                    this.chooseLocation()
                }).catch(error => {
                    this.setState({showModal: true})
                })
            }
        }).catch(error => {
            console.error('Taro.getSetting() failed!!', error)
        })
    }

    handleOpenSetting(e) {
        this.setState({
            showModal: false
        })
        const permitted = e.detail.authSetting[SCOPE_USERLOCATION]
        if (permitted)
            this.chooseLocation()
    }

    handleCloseCreatorSuccessModal(goToIndex) {
        this.props.closeCreateSuccessModal()
        if(goToIndex){
            this.props.onSwitchTab(0)
        }
    }

    chooseLocation() {
        Taro.chooseLocation().then(res => {
            this.props.changeFormMultipart({
                address: res.address,
                latitude: res.latitude,
                longitude: res.longitude
            })
        }).catch(error => {
            // 取消选点 不做处理
            console.log(error)
        })
    }

    config = {
        navigationBarTitleText: '创建课程'
    }

    render() {
        const {form} = this.props

        return (
            <View className='create-event'>
                <AtForm className='form-body' onSubmit={this.handleFormSubmit.bind(this)}>
                    <AtInput
                        name='title'
                        title='课程名称：'
                        type='text'
                        placeholder=''
                        value={form.title}
                        onChange={this.handleChange.bind(this, 'title')}
                    />
                    <View className='event-title-row'>
                        <Text className='event-title'>课程描述：</Text>
                    </View>
                    <AtTextarea
                        count={false}
                        textOverflowForbidden={false}
                        name='description'
                        value={form.description}
                        onChange={this.handleTextareaChange.bind(this, 'description')}
                        maxLength={200}
                        placeholder=''
                    />

                    <View className='event-title-row'>
                        <Text className='event-title'>课程议程：</Text>
                    </View>
                    <AtTextarea
                        count={false}
                        textOverflowForbidden={false}
                        value={form.event_agenda}
                        onChange={this.handleTextareaChange.bind(this, 'event_agenda')}
                        maxLength={200}
                        placeholder=''
                    />

                    <AtImagePicker
                        files={form.pickedImages}
                        onChange={this.handleImageChange.bind(this)}
                        multiple={false}
                        showAddBtn={form.pickedImages.length === 0}
                    />
                    <Text className='event-desc-title'>上传一张Banner图片800*1600像素</Text>

                    <View className='at-row date-select'>
                        <View className='at-col at-col-7'>
                            <Picker mode='date' name='startDate'
                                    onChange={this.handleTextareaChange.bind(this, 'startDate')}>
                                <View className='picker'>
                                    <View className='date-list-item'>
                                        <View className='date-list-item__label'>开始日期：</View>
                                        <View className='date-list-item__value'>{form.startDate}</View>
                                    </View>
                                </View>
                            </Picker>
                        </View>
                        <View className='at-col at-col-5'>
                            <Picker mode='time' name='startTime'
                                    onChange={this.handleTextareaChange.bind(this, 'startTime')}>
                                <View className='picker'>
                                    <View className='date-list-item'>
                                        <View className='date-list-item__label'>开始时间：</View>
                                        <View className='date-list-item__value'>{form.startTime}</View>
                                    </View>
                                </View>
                            </Picker>
                        </View>
                    </View>

                    <View className='at-row date-select'>
                        <View className='at-col at-col-7'>
                            <Picker mode='date' name='endDate'
                                    onChange={this.handleTextareaChange.bind(this, 'endDate')}>
                                <View className='picker'>
                                    <View className='date-list-item'>
                                        <View className='date-list-item__label'>结束日期：</View>
                                        <View className='date-list-item__value'>{form.endDate}</View>
                                    </View>
                                </View>
                            </Picker>
                        </View>
                        <View className='at-col at-col-5'>
                            <Picker mode='time' name='endTime'
                                    onChange={this.handleTextareaChange.bind(this, 'endTime')}>
                                <View className='picker'>
                                    <View className='date-list-item'>
                                        <View className='date-list-item__label'>结束时间：</View>
                                        <View className='date-list-item__value'>{form.endTime}</View>
                                    </View>
                                </View>
                            </Picker>
                        </View>
                    </View>

                    <AtInput
                        name='place'
                        title='场地名称：'
                        type='text'
                        placeholder=''
                        value={form.place}
                        onChange={this.handleChange.bind(this, 'place')}
                    />
                    <View className="at-row address-selector">
                        <View className="at-col-2 address-selector-label">地址：</View>
                        <View className="at-col-8 address-selector-right"
                              onClick={this.handleClickChooseMap.bind(this)}>
                            <View className='at-icon at-icon-map-pin'/>
                            <Text>{form.address}</Text>
                        </View>
                    </View>
                    <AtButton formType='submit'>提交</AtButton>
                </AtForm>
                <AtModal isOpened={this.state.showModal}>
                    <AtModalHeader>提示</AtModalHeader>
                    <AtModalContent>
                        <Button openType='openSetting'
                                onOpenSetting={this.handleOpenSetting.bind(this)}>点我打开setting！</Button>
                    </AtModalContent>
                    <AtModalAction>
                        <Button onClick={() => this.setState({showModal: false})}>取消</Button>
                    </AtModalAction>
                </AtModal>
                <AtModal isOpened={this.props.showCreateSuccessModal}>
                    <AtModalHeader>创建成功！</AtModalHeader>
                    <AtModalContent>
                        <Button onClick={this.handleCloseCreatorSuccessModal.bind(this,true)}>前往首页</Button>
                    </AtModalContent>
                    <AtModalAction>
                        <Button onClick={this.handleCloseCreatorSuccessModal.bind(this,false)}>继续创建</Button>
                    </AtModalAction>
                </AtModal>
            </View>
        )
    }
}

// createCourse

const mapStateToProps = ({courseList}) => {
    return {
        form: courseList.creatorForm,
        showCreateSuccessModal: courseList.showCreateSuccessModal
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        ...bindActionCreators(courseListActions, dispatch),
        ...bindActionCreators(tabPageActions,dispatch)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Creator)